﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace FileManager_Server.BusinessLogic.Respository_Service
{
    public class FileUtility
    {
        #region File Hash Code
        public static string Md5File(string fileName)
        {
            return HashFile(fileName, "md5");
        }

        private static string ByteArrayToHexString(ICollection<byte> bytes)
        {
            var length = bytes.Count;
            var builder = new StringBuilder();
            foreach (var num in bytes)
            {
                builder.Append(Convert.ToString(Convert.ToInt32(num), 0x10));
            }
            return builder.ToString();
        }

        private static byte[] HashData(Stream stream, string algName)
        {
            HashAlgorithm algorithm;
            if (algName == null)
            {
                throw new ArgumentNullException("algName 不能为 null");
            }
            if (String.Compare(algName, "sha1", StringComparison.OrdinalIgnoreCase) == 0)
            {
                algorithm = SHA1.Create();
            }
            else
            {
                if (String.Compare(algName, "md5", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    throw new Exception("algName 只能使用 sha1 或 md5");
                }
                algorithm = MD5.Create();
            }
            return algorithm.ComputeHash(stream);
        }

        private static string HashFile(string fileName, string algName)
        {
            if (!File.Exists(fileName))
            {
                return string.Empty;
            }
            var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var bytes = HashData(stream, algName);
            stream.Close();
            return ByteArrayToHexString(bytes);
        }

        public static string Md5File(FileStream fs)
        {
            return ByteArrayToHexString(HashData(fs, "md5"));
        }
        #endregion
    }
}